package com.woniuxy.mail.rabbit_demo.service.impl;

import com.woniuxy.mail.rabbit_demo.service.EmailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.util.Date;

/**
 * @Description:
 * @Author:l
 * @Date:2022.02.18
 */
@Service
public class EmailServiceImpl implements EmailService {
    @Autowired
    private JavaMailSender javaMailSender;

    @Autowired
    private TemplateEngine templateEngine;

    /**
     * 发送邮件
     * @param Title 邮件标题
     * @param context 模板共享数据
     * @param sender 发件人邮箱
     * @param accepter 收件人邮箱
     * @throws MessagingException
     */
    public void sendEmail(String Title, Context context, String sender, String accepter,String emailTemplate) throws MessagingException {

        MimeMessage mimeMessage = javaMailSender.createMimeMessage();

        MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage, true);
        //邮件标题
        mimeMessageHelper.setSubject(Title);

        //操作html的类
//        Context context = new Context();
//        context.setVariable("account", "陈翔");
        //将html转成字符串发到邮箱

        String process = templateEngine.process(emailTemplate, context);

        //true开启html

        mimeMessageHelper.setText(process, true);

//        發件人
//        sender = "lzl1248782426@163.com";
        mimeMessageHelper.setFrom(sender);

        mimeMessageHelper.setSentDate(new Date());

        //收件人
        mimeMessageHelper.setTo(accepter);
        javaMailSender.send(mimeMessage);

    }
}

